using System;
using System.Collections;
using System.Collections.Specialized;
using System.Xml.XPath;

using Actions;
using Actions.Connectors;
using Actions.Security;

namespace Actions.Usecases
{
	/// <summary>
	/// Description of UsecasesPool.
	/// </summary>
	public class UsecasesPool
	{
		private ArrayList		_us;
		
		public UsecasesPool(ref Document d)
		{
			XPathNodeIterator i = d.Select("//Configuration/UsecasesPool/UsecaseSet");
			
			_us = new ArrayList();
			while(i.MoveNext()) {
				_us.Add(new UsecaseSet(i.Current.GetAttribute("assembly", ""), 
				   Boolean.Parse(i.Current.GetAttribute("mustBeLoaded", "")), 
				   Boolean.Parse(i.Current.GetAttribute("public", "")),
				   i.Current.GetAttribute("title", ""))
				 );
			}
		}
		
		public void execute(ref IConnector c) 
		{
			IEnumerator i = _us.GetEnumerator();
			SecurityAgent sa = new SecurityAgent();
			
			sa.init(ref c);

            bool exc = false;
		    
		    // Iterate on public sets
			while(i.MoveNext()) {
			    if ((i.Current as UsecaseSet).isPublic)
			       exc = (i.Current as UsecaseSet).execute(ref c, sa);
			    if(exc) break;
			}
			
			// If no public set's execution - use non-public sets
			if(!exc) {
   			   i.Reset();
			
			   while(i.MoveNext()) {
			       if (!(i.Current as UsecaseSet).isPublic)
			          exc = (i.Current as UsecaseSet).execute(ref c, sa);
			       if(exc) break;
			   }
			}
		}
		
		public ArrayList getUsecasesList()
		{
		    ArrayList res = new ArrayList();
		    
			IEnumerator i = _us.GetEnumerator();
			while(i.MoveNext()) {
			    res.AddRange((i.Current as UsecaseSet).getUsecasesList());
			}
		    return res;
		}

		public string getUsecasesListXML()
		{
		  	string s = "<usecasepool>";
		    
			IEnumerator i = _us.GetEnumerator();
			while(i.MoveNext()) {
			    s += (i.Current as UsecaseSet).getUsecasesListXML();
			}
			s += "</usecasepool>";
			
		    return s;
		}

	}
}
